<?php


namespace app\api\controller;


//购物车
use app\common\lib\Show;


class Cart extends AuthBase
{
    //加入购物车方法
    public function add()
    {
        if (!$this->request->isPost()) {
            return Show::error();
        }
        $id = input("param.id", 0, "intval");
        $num = input("param.num", 0, "intval");
        if (!$id || !$num) {
            return Show::error( "参数不合法");
        }
        //加入购物车逻辑
        $res = (new \app\common\business\Cart())->insertRedis($this->userId, $id, $num);
        if ($res === FALSE) {
            return Show::error();
        }
        return Show::success($res);
    }

    /**
     * 购物车页面 adn 订单提交页面 不传ids就是购物车页面
     * @return \think\response\Json
     */
    public function lists()
    {

        //订单提交页面获取ID
        $ids = input("param.id", "", "trim");

        $res = (new \app\common\business\Cart())->lists($this->userId,$ids);


        if ($res === FALSE) {
            return Show::error();
        }
        return Show::success($res);

    }


    //修改购物车数量
    public function update()
    {
        if (!$this->request->isPost()) {
            return Show::error();
        }
        $id = input("param.id", 0, "intval");
        $num = input("param.num", 0, "intval");
        if (!$id || !$num) {
            return Show::error( '参数不合法');
        }

        try {
            $res = (new \app\common\business\Cart())->updateRedis($this->userId, $id, $num);
        } catch (\Exception $e) {
            return Show::error($e->getMessage());
        }

        if ($res === FALSE) {
            return Show::error();
        }
        return Show::success($res);

    }


    //删除购物车
    public function delete()
    {
        if (!$this->request->isPost()) {
            return Show::error();
        }
        $id = input("param.id", 0, "intval");
        if (!$id) {
            return Show::error( '参数不合法');
        }

        $res = (new \app\common\business\Cart())->deleteRedis($this->userId, $id);
        if ($res === FALSE) {
            return Show::error();
        }
        return Show::success($res);
    }

}